package com.oceansoft.mobile.econsole.modules.api.controller;

import com.alibaba.fastjson.JSONArray;
import com.oceansoft.mobile.econsole.exam.entity.Attach;
import com.oceansoft.mobile.econsole.exam.entity.ExamTest;
import com.oceansoft.mobile.econsole.exam.entity.QuestionsExt;
import com.oceansoft.mobile.econsole.exam.service.IExamService;
import com.oceansoft.mobile.econsole.modules.api.service.IDoExamService;
import com.oceansoft.mobile.econsole.modules.base.controller.BaseController;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import javax.annotation.Resource;
import javax.imageio.ImageIO;
import javax.servlet.http.HttpServletResponse;
import java.awt.image.BufferedImage;
import java.io.*;
import java.util.List;

import static org.springframework.web.bind.annotation.RequestMethod.GET;

/**
 * Created by liujie on 2016/8/18.
 */
@Controller
@RequestMapping("api/exam")
public class ApiExamController extends BaseController {
    @Resource
    IDoExamService doExamService;
    @Resource
    IExamService examService;

    @RequestMapping(value = "index/{examid}", method = GET)
    public String getIndex(@PathVariable("examid") String examId, Model model) {
        ExamTest exam = examService.getExamTestById(Integer.parseInt(examId));
        List<QuestionsExt> questionList = doExamService.getQuestionsForAExam(exam);
        int count = exam.getSinglenum() + exam.getMultiplenum() + exam.getJudgenum();
        model.addAttribute("exam",exam);
        model.addAttribute("count",count);
        model.addAttribute("questionList", JSONArray.toJSONString(questionList));
        return "exam/do-exam";
    }

    @RequestMapping(value = "image/{id}", method = GET)
    public void getImage(@PathVariable("id") String id, HttpServletResponse response){
        try {
            Attach attach = examService.getAttachById(Integer.parseInt(id));
            InputStream is = new ByteArrayInputStream(attach.getContent());
            if (is != null) {
                is = new BufferedInputStream(is);
                BufferedImage bi = ImageIO.read(is);
                OutputStream os = response.getOutputStream();
                ImageIO.write(bi,"png",os);
            }
        }
        catch (IOException e){
            e.printStackTrace();
        }
    }
}
